package com.aviccxzx.smarthome.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.aviccxzx.smarthome.entity.FeedBack;
import com.aviccxzx.smarthome.entity.FenceData;
import com.aviccxzx.smarthome.entity.SceneListAskBean;
import com.aviccxzx.smarthome.netutil.app.App;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by joey on 2017/3/22.
 */

public class AmapLocService extends Service {
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = new AMapLocationClientOption();
    Timer mTimer;
    boolean gatepos;
    String uid, mac, imei;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        gatepos = intent.getBooleanExtra("gatePos", false);
        uid = intent.getStringExtra("Uid");
        mac = intent.getStringExtra("gatemac");
        imei = intent.getStringExtra("Imei");
        return super.onStartCommand(intent, flags, startId);
    }

    AMapLocation mloc;
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //需要循环执行的代码
                    syncLocation(mloc);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        mTimer = new Timer();
        initLocation();
        startLocation();
        super.onCreate();
    }


    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        //设置定位参数
        locationClient.setLocationOption(getDefaultOption());
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(5000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            Message msg = new Message();
            msg.what = 1;
            handler.sendMessage(msg);
        }
    };

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(final AMapLocation loc) {
            if (null != loc) {
                if (gatepos) {
                    //添加网关后上传位置
                    setPos(loc);
                } else {
                    //解析定位结果
                    int errorCode = loc.getErrorCode();
                    if (errorCode==13){

                    }
                    mloc = loc;
                    //5s响一次
                    mTimer.schedule(timerTask, 0, 10000);
                }
               /* new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        App.getApp().showToast(locResult);
                        Log.d("uid.............",locResult);
                        //同步位置信息
                        syncLocation(loc);
                    }
                }, 5000);*/
            } else {
                App.getApp().showToast("定位失败");
            }
        }
    };

    public void setPos(AMapLocation loc) {
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Gson gson = new Gson();

        FenceData data = new FenceData();
        data.setDistance(500);
        data.setLatitude(loc.getLatitude() + "");
        data.setLongitude(loc.getLongitude() + "");

        List<FenceData.ElectronicScenesBean> electronicScenes = new ArrayList();
        FenceData.ElectronicScenesBean electronicScenesBean = new FenceData.ElectronicScenesBean();
        electronicScenesBean.setScene_id("1");
        electronicScenesBean.setScene_switch(1);
        electronicScenes.add(electronicScenesBean);
        data.setElectronicScenes(electronicScenes);

        FenceData.FrontDtoBean frontDtoBean = new FenceData.FrontDtoBean();
        frontDtoBean.setUid(uid);
        frontDtoBean.setMac(mac);
        frontDtoBean.setImei(imei);
        data.setFrontDto(frontDtoBean);


        String strEntity = gson.toJson(data);

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), strEntity);
        Call<FeedBack> call = service.setElectronicFence(body);
        call.enqueue(new Callback<FeedBack>() {
            @Override
            public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                //关闭定位
                stopSelf();
            }

            @Override
            public void onFailure(Call<FeedBack> call, Throwable t) {
                //关闭定位
                stopSelf();
            }
        });
    }

    private void syncLocation(AMapLocation loc) {
        SharedPreferences spf = getSharedPreferences("set", Context.MODE_PRIVATE);
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Gson gson = new Gson();

        String uid = spf.getString("Uid", "");
        String Mac = spf.getString("gatemac", "");
        String imei = spf.getString("Imei", "");

        SceneListAskBean scene = new SceneListAskBean();
        scene.setImei(imei);
        scene.setMac(Mac);
        scene.setUid(uid);

        String strEntity = gson.toJson(scene);

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        Call<ResponseBody> call = service.syncUserLocation(body, loc.getLongitude() + "", loc.getLatitude() + "");
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
        //        spf.edit().putString("lat",loc.getLatitude()+"").commit();
        //        spf.edit().putString("long",loc.getLongitude()+"").commit();
    }

    /**
     * 开始定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {
        //根据控件的选择，重新设置定位参数
        //        resetOption();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocation();
        destroyLocation();
        mTimer.cancel();
    }

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @Override
    public boolean stopService(Intent name) {
        stopLocation();
        destroyLocation();
        return super.stopService(name);
    }
}
